package com.tzz.utils;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;

public class ProducerMQUtil {

    public static DefaultMQProducer getProducer(String producerGroup){
        return new DefaultMQProducer(producerGroup);
    }

    public static <T> void sendMsg(DefaultMQProducer producer,String address, String topic, T data){
        producer.setNamesrvAddr(address);
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        Message msg = new Message();
        msg.setTopic(topic);
        if (topic.equals("kamsCommonTopic")){
            msg.setTags("keyAccountOrderInit");
        }
        msg.setBody(data.toString().getBytes(StandardCharsets.UTF_8));
        try {
            producer.send(msg);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            producerShutDown(producer);
        }
    }


    public static void producerShutDown(DefaultMQProducer producer){
        producer.shutdown();
    }
}
